package redis

import (
	"strconv"
	"strings"

	goRedis "github.com/gomodule/redigo/redis"
)

type redis struct {
	network  string
	port     int
	host     string
	password string
}

var Redis = new(redis)

func (redis *redis) Connect() (goRedis.Conn, error) {
	host := redis.host
	if host == "" {
		host = "127.0.0.1"
	}

	if redis.network == "" {
		redis.network = "tcp"
	}

	if redis.port == 0 {
		redis.port = 6379
	}

	c, err := goRedis.Dial(redis.network, strings.Join([]string{host, ":", strconv.Itoa(redis.port)}, ""))
	if err != nil {
		panic(err.Error())
		return nil, err
	}

	if _, err := c.Do("AUTH", "gufengxiu10"); err != nil {
		c.Close()
		panic(err.Error())
		return nil, err
	}

	if _, err := c.Do("SELECT", 0); err != nil {
		c.Close()
		panic(err.Error())
		return nil, err
	}

	return c, nil
}

func (redis *redis) SetNetwork(network string) *redis {
	redis.network = network
	return redis
}

func (redis *redis) SetHost(host string) *redis {
	redis.host = host
	return redis
}

func (redis *redis) SetPassword(password string) *redis {
	redis.password = password
	return redis
}
